#导入蓝图模块
import re
from flask import Blueprint,request,json,jsonify
#注册蓝图模块
bp_city=Blueprint("city",__name__)

#导入数据库
from db import db1

#导入文件操作模块
import os

#导入文件操作的配置文件
from utils.myfile import myfile


#城市表操作
@bp_city.route('/cityM',methods=['POST','GET'])
def cityM():
    if request.method=='GET':
        #构造sql语句
        sql="select * from city"
        res=db1.findall(sql)
        #返回
        return jsonify({'code':200,'list':res})


#文件上传
@bp_city.route('/upload',methods=['POST'])
def upload():
    #获取用户上传的文件
    file=request.files['file']
    print(file)
    #获取用户上传的城市id
    city_id=request.form['city_id']
    #创建文件夹
    myfile.file_mkdir(city_id)
    #图片上传
    file.save(os.path.join('./static/upload/'+str(city_id),file.filename))
    # 返回 图片地址=文件位置+文件名
    return jsonify({'code':200,'url':'/static/upload/'+str(city_id)+'/'+file.filename})




#产品表操作
@bp_city.route('/produatA',methods=['POST','GET'])
def produatA():
    if request.method=='POST':
        data=request.data
        if data:
            data=json.loads(data)
        else:
            data=request.form
        #构造sql语句
        sql="insert into product(name,price,city_id,pic) values('%s',%.2f,%d,'%s')"%(data['name'],float(data['price']),int(data['city_id']),data['pic'])
        db1.insert(sql)
        #返回
        return jsonify({'code':200})